package com.example.userdepartment.controller;

import com.example.userdepartment.common.Result;
import com.example.userdepartment.service.AuthService;
import com.example.userdepartment.vo.AuthVO;
import com.example.userdepartment.vo.LoginVO;
import com.example.userdepartment.vo.RegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户注册
     * @param registerVO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterVO registerVO) {
        try {
            AuthVO authVO = authService.register(registerVO);
            return ResponseEntity.ok(Result.success(authVO, "注册成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Result.error(e.getMessage()));
        }
    }

    /**
     * 用户登录
     * @param loginVO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginVO loginVO) {
        try {
            AuthVO authVO = authService.login(loginVO);
            return ResponseEntity.ok(Result.success(authVO, "登录成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Result.error(e.getMessage()));
        }
    }

    /**
     * 检查用户名是否存在
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/check-username")
    public ResponseEntity<?> checkUsername(@RequestParam String username) {
        boolean exists = authService.existsByUsername(username);
        return ResponseEntity.ok(Result.success(exists));
    }

    /**
     * 检查邮箱是否存在
     * @param email 邮箱
     * @return 检查结果
     */
    @GetMapping("/check-email")
    public ResponseEntity<?> checkEmail(@RequestParam String email) {
        boolean exists = authService.existsByEmail(email);
        return ResponseEntity.ok(Result.success(exists));
    }
} 